package ua.edu.nuos.jeetraining2012.cms.servlet;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import ua.edu.nuos.jeetraining2012.cms.entity.UserEntity;
import ua.edu.nuos.jeetraining2012.cms.util.interceptor.ShiroSecurity;
import ua.edu.nuos.jeetraining2012.cms.util.servlet.CmsServlet;
import ua.edu.nuos.jeetraining2012.cms.util.template.TemplateRenderer;
import ua.edu.nuos.jeetraining2012.cms.util.template.homework.ViewTemplate;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Homework servlet.
 * <p/>
 *
 *
 * @author Victor N. Ganichev victor.ganichev@gmail.com
 * @version 1.0 Date: 24.06.13 Time: 10:29
 * @since 1.0
 */
@ShiroSecurity
@WebServlet(urlPatterns = {"/homework", "/homework/*"})
public class HomeWorkServlet extends CmsServlet {

    /** Define current controller name. */
    final private static String CURRENT_CONTROLLER = "homework";


    /** Define logger. */
    final private static Logger logger = org.slf4j.LoggerFactory.getLogger(HomeWorkServlet.class);

    public void viewAction(HttpServletRequest request, HttpServletResponse response) throws IOException {
        logger.debug("viewAction() - started.");

        final Subject subject = SecurityUtils.getSubject();

        if (subject == null || !subject.isAuthenticated()) {
            logger.debug("User not authenticated. Redirecting to /");
            response.sendRedirect(request.getContextPath() + "/");
            return;
        }

        UserEntity user = (UserEntity) subject.getSession().getAttribute("user");
        if (user == null) {
            logger.debug("Invalid UserEntity. Redirecting to /");
            response.sendRedirect(request.getContextPath() + "/");
            return;
        }

        final String ACTION_NAME = "view";
        String hwIdReq = request.getParameter("homework_id");
        String currentCollapseNumReq = request.getParameter("si");
        Integer currentCollapseNum = (currentCollapseNumReq == null)
                ? 0
                : Integer.valueOf(currentCollapseNumReq);

        Long homeWorkId = null;

        if (hwIdReq == null || hwIdReq.isEmpty()) {
            logger.debug("No homework id was sent, redirecting to course list.");
            try {
                response.sendRedirect(request.getContextPath() + "/");
                return;
            } catch (IOException e) {
                logger.error("Can't redirect to course list. Got error: {}, \nTrace:\n {}", e.getMessage(),
                        e.getStackTrace());
            }
        } else {
            homeWorkId = Long.valueOf(hwIdReq);
            logger.debug("Ready to show hw with ID {}", homeWorkId);
        }


        TemplateRenderer renderer = new TemplateRenderer();
        ViewTemplate template = new ViewTemplate(homeWorkId);
        template.setCurrentController(CURRENT_CONTROLLER);
        template.setCurrentAction(ACTION_NAME);
        template.setCurrentCollapseNum(currentCollapseNum);
        template.setContextPath(request.getContextPath());


        if (!renderer.process(template, response.getWriter())) {
            try {
                request.getRequestDispatcher("/error.jspx").forward(request, response);
            } catch (ServletException e) {
                logger.error("loginAction() - Can't forward to error.jspx", e);
            }
        }

        logger.debug("viewAction() - finished.");
    }
}
